import 'dart:async';
import 'dart:io';
import 'package:chewie/chewie.dart';
import 'package:dio/dio.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/lc_video_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/text/expandable_text.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/drawer_page.dart';
import 'package:lcapp/page/home/home.dart';
import 'package:lcapp/page/home/home_comment_page.dart';
import 'package:lcapp/page/home/home_share_img_page.dart';
import 'package:lcapp/page/home/home_share_page.dart';
import 'package:lcapp/widget/asr_cache_image.dart';
import 'package:lcapp/widget/lc_gesture_detector.dart';
import 'package:video_player/video_player.dart';
import 'package:path_provider/path_provider.dart';

bool isHomeShare = true; //首页的任务中心是否显示

class HomeVideoItem extends StatefulWidget {
  final int tabindex;
  final LcVideoDataEntity entity;
  final bool isMine;
  final Function clickFun;
  final List<LcVideoDataEntity> videos;
  const HomeVideoItem(this.tabindex,{Key? key, required this.entity, this.isMine=false,required this.clickFun,required this.videos,}) : super(key: key);

  @override
  _HomeVideoItemState createState() => _HomeVideoItemState();
}

class _HomeVideoItemState extends State<HomeVideoItem> {
  late VideoPlayerController _controller;
  bool isPause = false;
  late StreamSubscription _subscription;
  late StreamSubscription _shareSub;
  double progress = 0.0;
  String? location;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = VideoPlayerController.network(widget.entity.videoUrl!)
      ..initialize().then((value) {
        _controller?.play();
        _controller?.addListener(listener);
      });
    _shareSub = eventBus.on<ShareResultEvent>().listen((event){
      if(event.shareId==widget.entity.id){
        setState(() {
          widget.entity.share = widget.entity!.share! + 1;
        });
      }
    });
        _subscription = eventBus.on<HomeChangeIndex>().listen((event) {
      setState(() {
        if(event.canPlay && homeTabIndex == widget.tabindex){
          _controller?.play();
          isPause=false;
        }else{
          _controller?.pause();
          isPause=true;
        }
      });
    });
    _addPlayViews();
    if(widget.entity.address!=null&&widget.entity.address!.isNotEmpty){
      List arr = widget.entity.address!.split(' ');
      print('arr====='+arr.toString());
      if(arr.length>=3){
        location = arr[2]??'';
      }else{
        location = widget.entity.address;
      }
    }
  }

  @override
  void didUpdateWidget(covariant HomeVideoItem oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if(oldWidget.entity.id!=widget.entity.id){
      _controller.removeListener(listener);
      _controller.dispose();
      _controller = VideoPlayerController.network(widget.entity.videoUrl!)
        ..initialize().then((value) {
          _controller.play();
          _controller.addListener(listener);
        });
    }
  }

  _addPlayViews(){
     HomeAPI.addPlayVideoViews(widget.entity.id!);
  }

  _likeVideo()async{
    ResponseData res = await HomeAPI.likeVideo(widget.entity.id!,widget.entity.userId!);
    if(res.code==200){
      if(widget.entity.likeState==1){
        setState(() {
          widget.entity.likeState = 0;
          widget.entity.likeCounts = widget.entity.likeCounts!-1;
        });
      }else{
        setState(() {
          widget.entity.likeState=1;
          widget.entity.likeCounts = widget.entity.likeCounts!+1;
        });
      }
    }
  }

  void listener() {
    //监听进度
    setState(() {
      progress = _controller.value.position.inSeconds /
          _controller.value.duration.inSeconds;
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.removeListener(listener);
    _controller.dispose();
    _subscription.cancel();
    _shareSub.cancel();
  }

  pushPageName(String name,{dynamic arguments}){
    _controller.pause();
    Navigator.of(context).pushNamed(name,arguments: arguments).then((value){
      _controller.play();
      if(value is Map){
        setState(() {
          if(value['attentionState']!=null){
            widget.entity.attentionState = value['attentionState'];
            for (var element in widget.videos) {
              if(element.userId==widget.entity.userId){
                element.attentionState = value['attentionState'];
              }
            }
          }
        });
      }
      if(widget.clickFun!=null){
        widget.clickFun(5);
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Positioned(child:
          GestureDetector(
            onTap: (){
              if(sliderDrawerKey.currentState!=null){
                sliderDrawerKey.currentState?.closeSlider();
                eventBus.fire(HomeSliderChangeIndex(isOpen:false));
              }
              setState(() {
                if (!isPause) {
                  _controller.pause();
                  isPause = true;
                } else {
                  _controller.play();
                  isPause = false;
                }
              });
            },
            child: SizedBox.expand(
              child: FittedBox(
                fit: BoxFit.fill,
                child: SizedBox(
                    width: 1.sw,
                    height: 1.sh,
                    child: Container(
                      width: 1.sw,
                      height: 1.sh,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: NetworkImage(widget.entity.videoUrl! + '?x-oss-process=video/snapshot,t_1000,m_fast'),
                              fit:  _controller.value.aspectRatio > 1? BoxFit.fitWidth :  BoxFit.fill
                          )
                      ),
                      child: Stack(
                        children: [
                          // Visibility(child: Container(
                          //   child: ExtendedImage.network(
                          //     widget.entity.videoUrl + '?x-oss-process=video/snapshot,t_1000,m_fast',
                          //     width: 1.sw,
                          //     height: 1.sh,
                          //     fit: BoxFit.fitWidth,
                          //     cache: true,
                          //   ),
                          // ),visible: !_controller.value.isInitialized,),
                          Visibility(child: Center(
                              child: SizedBox.expand(
                                child: FittedBox(
                                  fit: BoxFit.fill,
                                  child: SizedBox(
                                      width: 1.sw,
                                      height: 1.sh,
                                      child:  Chewie(controller: ChewieController(
                                        videoPlayerController: _controller,
                                        // 根据视频纵横比设置
                                        aspectRatio: _controller.value.aspectRatio < 1? 1.sw/1.sh:_controller.value.aspectRatio,
                                        autoPlay: false,
                                        looping: true,
                                        allowedScreenSleep: false,
                                        allowPlaybackSpeedChanging: false,
                                        showControls: false,
                                        // 初始状态不显示控制器
                                        showControlsOnInitialize: _controller.value.isInitialized,
                                      )),
                                  ),
                                ),
                              )
                          ),visible: _controller.value.isInitialized,),
                          Visibility(child: Center(
                            child: Container(
                              //放按钮
                              height: 100.w,
                              width: 100.w,
                              child: Image.asset('assets/home/home_play.png',width: 100.w,),
                            ),
                          ),visible: isPause&&!_controller.value.isPlaying,),
                          Visibility(child: Center(
                            child: Container(
                              child: Image.asset(
                                'assets/home/asr_loading.gif',
                                fit: BoxFit.fitWidth,
                                width: 45.w,
                              ),
                            ),
                          ),visible: !_controller.value.isInitialized,),
                          Positioned(
                            child: Visibility(
                              child: Container(
                                  width: 1.sw,
                                  height: 60.w,
                                  child: SliderTheme(
                                    data: const SliderThemeData(
                                      /// 轨道的高度
                                      trackHeight: 1,
                                      /// 滑块左侧的颜色
                                      activeTrackColor: Color(0xFFFF6E47),

                                      /// 滑块右侧的颜色
                                      inactiveTrackColor: Color(0x60FFFFFF),

                                      /// 滑块的颜色
                                      thumbColor: Color(0xFFFF6E47),

                                      /// 滑块的形状和尺寸
                                      thumbShape:
                                      RoundSliderThumbShape(enabledThumbRadius: 0.5),
                                      /// 点击滑块后的特效的颜色
                                      overlayColor: Colors.transparent,

                                      /// 点击滑块后的特效的形状和尺寸
                                      overlayShape:
                                      RoundSliderOverlayShape(overlayRadius: 0.0),
                                    ),
                                    child: Slider(
                                        value: progress,
                                        onChanged: (value) {
                                          setState(() {
                                            progress = value;
                                            _controller
                                                .seekTo(_controller.value.duration * progress);
                                          });
                                        }),
                                  )),
                              visible: _controller.value.isInitialized,
                            ),
                            bottom: 0,
                            left: 0,
                            right: 0,
                          )
                        ],
                      ),
                    )
                  // Chewie(controller: ChewieController(
                  //   videoPlayerController: _controller,
                  //   // 根据视频纵横比设置
                  //   aspectRatio: _controller.value.aspectRatio,
                  //   autoPlay: false,
                  //   looping: true,
                  //   allowedScreenSleep: false,
                  //   allowPlaybackSpeedChanging: false,
                  //   showControls: false,
                  //   // 初始状态不显示控制器
                  //   showControlsOnInitialize: _controller.value.isInitialized,
                  // )),
                ),
              ),
            ),
          ),
            left: 0,right: 0,bottom: 0,top: 0,),
          Positioned(child: Container(
            child: Column(
              children: [
                GestureDetector(
                  onTap: (){
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 60.w),
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        GestureDetector(
                          onTap: (){
                            if(widget.entity.userId!=userInfo.id){
                              pushPageName('ShopHomePage',arguments: widget.entity.userId);
                            }
                          },
                          child: ClipRRect(
                            //圆角图片
                              borderRadius:
                              BorderRadius.circular(80.w),
                              child: Container(
                                color: Colors.white,
                                child: ASRCacheImage(image:widget.entity.img??'assets/icon/p_head.png',width: 100.w,height:100.w,fit: BoxFit.fitWidth,),
                              )
                          ),
                        ),
                        Positioned(child:
                        Visibility(
                          child: lcGestureDetector(
                              isLogin:true,
                              onTap: ()async{
                                ResponseData res = await UserAPI.followUser(widget.entity.userId!);
                                if(res.code==200){
                                  setState(() {
                                    widget.entity.attentionState = widget.entity.attentionState==1?0:1;
                                  });
                                }
                              },
                              child: Container(
                                child: widget.entity.attentionState ==1?Icon(Icons.check_box_rounded,color: defaultBarColor,size: 40.w,) :Image.asset("assets/home/homeadd.png",width: 30.w,),
                              )
                          ),visible: widget.entity.attentionState!=1&&widget.entity.userId!=userInfo.id,
                        ),bottom: -6.w,right: 35.w,)
                      ],
                    ),
                  ),
                ),
                lcGestureDetector(
                  isLogin:true,
                  onTap: (){
                    _likeVideo();
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 50.w),
                    child: Column(
                      children: [
                        Image.asset(widget.entity.likeState==1?"assets/home/xinxing_red.png":"assets/home/xinxing.png",height: 60.w,),
                        SizedBox(height: 15.w,),
                        Text("${widget.entity.likeCounts??'0'}",style: TextStyle(
                          color: Colors.white,
                          fontSize: 26.sp,
                          fontWeight: FontWeight.w600,
                          shadows: <Shadow>[
                            Shadow(
                              offset: Offset(1.0, 1.0),
                              blurRadius: 1.0,
                              color: Color.fromARGB(255, 0, 0, 0),
                            ),
                          ],
                        ),)
                      ],
                    ),
                  ),
                ),
                lcGestureDetector(
                  isLogin:true,
                  onTap: (){
                    SmartDialog.show(
                      alignment: Alignment.bottomCenter,
                      clickMaskDismiss: true,
                      maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                        return HomeCommentPage(entity: widget.entity,);
                    },
                    );
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 50.w),
                    child: Column(
                      children: [
                        Image.asset("assets/home/comment.png",width: 60.w,),
                        SizedBox(height: 15.w,),
                        Text("${widget.entity.comment??'0'}",style: TextStyle(
                            color: Colors.white,
                            fontSize: 26.sp,
                            fontWeight: FontWeight.w600,
                          shadows: <Shadow>[
                            Shadow(
                              offset: Offset(1.0, 1.0),
                              blurRadius: 1.0,
                              color: Color.fromARGB(255, 0, 0, 0),
                            ),
                          ],
                        ),)
                      ],
                    ),
                  ),
                ),
                lcGestureDetector(
                  isLogin:true,
                  onTap: (){
                    SmartDialog.show(
                      alignment: Alignment.bottomCenter,
                      clickMaskDismiss: true,
                      maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                        return HomeSharepage(
                          shareType: 2,
                          contentType: 1,
                          videoDataEntity: widget.entity,
                          shareUrl: '${BasVueurl}/#/video?lcID=${userInfo.id}&shareId=${widget.entity.id}',
                          aspectRadio:_controller.value.isInitialized?_controller.value.aspectRatio ?? 1.0:1.0,
                          map: {
                            'type':1,
                            'entryId':widget.entity.id
                          },
                          clickFun: (index)async{
                            if(index==1){ //保存本地
                              SmartDialog.dismiss();
                              showLoading();
                              final dir = await getTemporaryDirectory();
                              String path = dir.path + "/compress.mp4";
                              await Dio().download(widget.entity.videoUrl!, path,onReceiveProgress: (int count, int total){
                                print('total =' + total.toString() + 'count ====' + count.toString());
                              });
                              hideLoading();
                              ImageGallerySaverPlus.saveFile(path).then((value) {
                                showToast('保存成功~');
                                File file = File(path);
                                file.delete();
                              });
                            }
                            else if(index==2){ //生成图片
                              eventBus.fire(HomeChangeIndex(canPlay:false));
                              SmartDialog.show(
                                alignment: Alignment.bottomCenter,
                                clickMaskDismiss: true,
                                maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                                  return HomeShareImgPage(
                                    img: widget.entity.img,
                                  );
                              },
                              );
                            }
                            else if(index == 3){
                              Navigator.of(context).pushNamed('MinJuBaoPage',arguments: {
                                'type':1,
                                'entityId':widget.entity.id
                              });
                            }
                          },
                        );
                    },
                    );
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 50.w),
                    child: Column(
                      children: [
                        Image.asset("assets/home/share.png",width: 60.w,),
                        SizedBox(height: 15.w,),
                        Text("${widget.entity.share??'0'}",style: TextStyle(
                            color: Colors.white,
                            fontSize: 26.sp,
                            fontWeight: FontWeight.w600,
                          shadows: <Shadow>[
                            Shadow(
                              offset: Offset(1.0, 1.0),
                              blurRadius: 1.0,
                              color: Color.fromARGB(255, 0, 0, 0),
                            ),
                          ],
                        ),)
                      ],
                    ),
                  ),
                ),
                Visibility(child: GestureDetector(
                  onTap: (){
                    if(widget.clickFun!=null){
                      widget.clickFun(4);
                    }
                  },
                  child: Container(
                    child: Column(
                      children: [
                        Image.asset("assets/home/home_delete_w.png",width: 60.w,),
                        SizedBox(height: 15.w,),
                        Text("",style: TextStyle(
                            color: Colors.white,
                            fontSize: 26.sp,
                            fontWeight: FontWeight.w600
                        ),)
                      ],
                    ),
                  ),
                ),visible: widget.isMine,),
              ],
            ),
          ), width: 120.w,
            right: 10.w,top: widget.isMine? 1.sh - 600.h - 100.h-66.h:  (1.sh-550.h-66.h-ScreenUtil().bottomBarHeight)*0.5,),
          Positioned(child: GestureDetector(
            onTap: (){
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(child:GestureDetector(
                    onTap: (){
                      if(_controller.value.isInitialized){
                        if(sliderDrawerKey.currentState!=null){
                          sliderDrawerKey.currentState?.closeSlider();
                          eventBus.fire(HomeSliderChangeIndex(isOpen:false));
                        }
                        setState(() {
                          if (!isPause) {
                            _controller.pause();
                            isPause = true;
                          } else {
                            _controller.play();
                            isPause = false;
                          }
                        });
                      }
                    },
                    child: Container(
                      color: Colors.transparent,
                    ),
                  )),
                  Visibility(child: lcGestureDetector(
                    isLogin:true,
                    onTap: (){
                      pushPageName('HomeRenWuPage');
                    },
                    child: Container(
                        child: Stack(
                          clipBehavior: Clip.none,
                          children: [
                            Image.asset("assets/home/home_share.png",width: 200.w,),
                            Positioned(child:GestureDetector(
                              onTap: (){
                                setState(() {
                                  isHomeShare = false;
                                });
                              },
                              child:  Image.asset("assets/home/home_share_close.png",width: 35.w,),
                            ),right: 2,top: -5,)
                          ],
                        )
                    ),
                  ),visible: isHomeShare&&widget.isMine==false),
                  Visibility(child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20.w,vertical: 10.w),
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(0, 0, 0, 0.3),
                      borderRadius: BorderRadius.circular(10.w)
                    ),
                    margin: EdgeInsets.only(top: 50.w),
                    child: GestureDetector(
                      onTap: (){
                        pushPageName("XianHuoDetailPage",arguments: widget.entity.goodsId);
                      },
                      child: Row(
                        children: [
                          Visibility(child: ClipRRect(
                            borderRadius: BorderRadius.circular(10.w),
                            child: Container(
                              child: ASRCacheImage(image:widget.entity.goodsImage!,width: 60.w,height:60.w,fit: BoxFit.fill,),
                            ),
                          ),visible: widget.entity.goodsImage!=null,),
                          Container(
                            padding: EdgeInsets.only(left: 20.w),
                            child: Text(widget.entity.publishType==0?'卖':'买',style:TextStyle(
                                color: Colors.white,
                                fontSize: 30.sp
                            ),),
                          ),
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 20.w),
                            height: 30.w,
                            width: 2.w,
                            color: Colors.white,
                          ),
                          Container(
                            child: Text('${widget.entity.goodsName??''} ${location??''}',maxLines: 1,overflow: TextOverflow.ellipsis,style:TextStyle(
                                color: Colors.white,
                                fontSize: 30.sp
                            ),),
                          )
                        ],
                        mainAxisSize: MainAxisSize.min,
                      ),
                    ),
                  ),visible: widget.isMine==false&&widget.entity.goodsId!=null&&widget.entity.goodsName!=null,),
                  Container(
                    margin: EdgeInsets.only(top: 40.w),
                    child: Text(widget.entity.userName??'',style: TextStyle(
                        color: Colors.white,
                        fontSize: 38.sp
                    ),),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 21.w),
                    child: ExpandableText(
                      text:widget.entity.videoDesc??'',
                      style:TextStyle(
                          color: Colors.white,
                          fontSize: 28.sp
                      ),
                      maxLines: 2,
                      textAlign: TextAlign.left,
                      btnOpen: Container(child: Text('展开',style:TextStyle(
                          color: Colors.white,
                          fontSize: 24.sp
                      )),),
                      btnClose: Container(child: Text('收起',style:TextStyle(
                          color: Colors.white,
                          fontSize: 24.sp
                      )),),
                    ),
                  ),
                ],
              ),
            ),
          ),left: 10.w,right: 130.w,bottom: 60.w,top: 100.w,)
        ],
      )
    );
  }
}
